<?php
namespace app\recharge\model;

use app\index\model\DCharacter;
use app\recharge\model\Store;
use think\Db;
use think\Model;
use think\Request;

class Verify extends Model
{

    //自动写入时间戳字段
    protected $autoWriteTimestamp = 'timestamp';

    //自定义初始化
    protected function initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::initialize();
        $this->store = new Store();
    }

    //分页
    //
    private $_page = null;
    private $_rows = null;
    private $_offset = null;

    /**
     * 返回订单列表(主键列表，条件数组，闭包查询)
     *
     * @param    array $param 查询条件
     * @return   void
     */
    public function doList(Request $request)
    {

        $param = $request->param();

        $page = $param['page'];
        $start = $param['start'];
        $limit = $param['limit'];
        $offset = ($page - 1) * $limit;

        //日志类型及查询日期
        //dump($param);die;

        $character_id = array_key_exists("character_id", $param) ? $param['character_id'] : null;
        $channel_id = array_key_exists("channel_id", $param) ? $param['channel_id'] : null;
        $server_id = array_key_exists("server_id", $param) ? $param['server_id'] : null;
        $nickname = array_key_exists("nickname", $param) ? $param['nickname'] : null;
        $date = array_key_exists("date", $param) ? $param['date'] : null;
        $where = [];

        //按照日期查询
        //
        if (!empty($date)) {
            $map = "DATEDIFF(`create_time`,'{$date}') = 0 ";
        }else{
            $map = [];
        }

        //按照渠道ID查询
        //
        if (!empty($channel_id)) {
            $where['channel_id'] = $channel_id;
        }

        //按照服务器ID查询
        //
        if (!empty($server_id)) {
            $where['server_id'] = $server_id;
        }

        //按照角色ID或者昵称查询

        if (!empty($character_id)) {

            $where['character_id'] = $character_id;

        } else if (!empty($nickname)) {

            $info = DCharacter::where("`nickname`='{$nickname}'")
                ->field("`id`")
                ->find();

            if ($info) {
                $record = $info->getData();
                $where['character_id'] = $record['id'];
            }
        }

        try {

            //查询数据
            $result = self::all(function ($query) use ($offset, $limit, $where, $map) {

                $query->where($where)
                    ->where($map)
                    ->limit($offset, $limit)
                    ->order('update_time desc,create_time desc');
            });

            $rows = [];

            foreach ($result as $data) {

                $item = $data->getData();
                array_push($rows, $item);
            }

            //返回结果
            //
            $res = array();

            //查询数据总量
            //
            $total = self::where($where)->where($map)->count();

            if ($total > 0) {
                $res['rows'] = $rows;
                $res['total'] = $total;
            } else {
                $res['total'] = 0;
                $res['rows'] = array();
            }

            //请求类型返回
            return $res;

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 根据交易订单号获取验签状态
     * @DateTime 2018-03-14
     * @param    [type] $orderId [description]
     * @return   [type]
     */
    public function getVerifyStatusByOrderId($orderId)
    {

        $record = $this->get(function ($query) use ($orderId) {
            $query->where('orderId', $orderId);
        });

        //交易号存在
        //
        if ($record) {
            $data = array(
                "code" => 0,
                "msg" => "transaction id exist",
                "verify_status" => $record->verify_status,
            );

        } else {
            $data = array(
                "code" => 1,
                "msg" => "transaction id doesn't exist",
            );
        }
        return $data;
    }

    public function updatePaymentStatusByOrderId($orderId)
    {

        $record = Verify::get(function ($query) use ($orderId) {
            $query->where('orderId', $orderId);
        });

        //交易号已经存在
        //
        if ($record) {

            $res = $this->save([
                'payment_status' => 1,
            ], ['orderId' => $orderId]);

            if ($res) {
                $data = array(
                    "code" => 0,
                    "msg" => 'success',
                );
            } else {
                $data = array(
                    "code" => 1,
                    "msg" => 'false',
                );
            }

        } else {
            $data = array(
                "code" => 2,
                "msg" => "transaction id doesn't exist",
            );
        }
        return $data;
    }

    /**
     * 付费用户的角色ID数
     *
     * @param    string $date 计算日期
     * @return   int 统计数量
     */
    public function getPayUserTotal($date)
    {
        try {

            //查询某日付费角色ID数量
            //
            $res = Db::query("SELECT COUNT(DISTINCT `character_id`) AS `count` FROM `verify` WHERE DATEDIFF(`create_time`,'{$date}') = 0 AND `verify_status` = 1 AND `amount` > 0 LIMIT 1");
            $rtn = $res[0]['count'];

            return $rtn;

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 日付费总金额
     *
     * @param    string $date 计算日期
     * @return   int 统计数量
     */
    public function getPayTotal($date)
    {
        try {

            //查询某日付费角色ID数量
            //
            $res = Db::query("SELECT SUM(`amount`) AS `amount` FROM `verify` WHERE DATEDIFF(`create_time`,'{$date}') = 0 AND `verify_status` = 1 AND `amount` > 0 LIMIT 1");
            $rtn = $res[0]['amount'];

            return $rtn;

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }
}
